<?php
/**
 * IG_Auth
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Iwgame.php 1082 2011-12-09 09:27:48Z mmxie $
 */
class IG_Auth_Adapter_Iwgame implements Zend_Auth_Adapter_Interface
{
    /**
     *
     * @var Zend_Auth_Adapter_DbTable
     */
    private $_dbAuthAdapter;

    /**
     * Zend_Auth_Adapter_DbTable 配置
     * @var string
     */
    private $_dbAuthAdapterConfig = array(
        'table'             => 'sys_employee',
        'identityColumn'    => 'name',
        'credentialColumn'  => 'password',
    );

    private static $_verify = array(
        'sessionname' => 'verifycode',
        'enable'      => true,
    );

    private $_messages = array(
        Zend_Auth_Result::SUCCESS                    => '验证成功',
        Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS => '验证码不正确',
        Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND => '验证失败, 用户不存在',
        Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID => '验证失败, 密码不正确',
        Zend_Auth_Result::FAILURE                    => '验证失败',
    );

    private $_authResultConfig = array();

    private $_authParams = array();

    private $_employee;

    public function __construct ($identity, $credential, $verifycode = null, $passpod = null)
    {

        $this->_authResultConfig = array(
            'code'     => Zend_Auth_Result::FAILURE,
            'identity' => $identity,
            'message'  => ''
        );

        $this->_authParams = array(
            'identity'   => $identity,
            'credential' => $credential,
            'verifycode' => $verifycode,
            'passpod'    => $passpod,
        );
    }


    /**
     * 验证码、用户账号、密保验证
     * @return Zend_Auth_Result
     */
    public function authenticate ()
    {
        if ( $this->_checkVerify() && $this->_checkDbTable()
            && $this->_checkCryptoguard()) {

            $row = $this->_dbAuthAdapter->getResultRowObject(null, array(
                'last_login', 'last_error', 'error_times'
            ));

            $this->_getEmployee()
                 ->setEmployeeId((int) $row->employee_id)
                 ->setLastLogin(date('Y-m-d H:i:s'))
                 ->setErrorTimes(0)
                 ->save();
            $this->_getEmployee()
                 ->setOptions($row)
                 ->getRoles();

            $this->_authResultConfig['code'] = Zend_Auth_Result::SUCCESS;
            $this->_authResultConfig['identity'] = $this->_getEmployee();
            return $this->_authResult();
        }

        return $this->_authResult();
    }

    /**
     * 验证码验证
     * @return bool
     */
    protected function _checkVerify()
    {
        if (!self::isEnableVerify()) {
            return true;
        }

        $session = new Zend_Session_Namespace(self::$_verify['sessionname']);
        if ($session->word != $this->_authParams['verifycode']) {
            $this->_authResultConfig['code']    = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
            $this->_authResultConfig['message'] =
                $this->_messages[Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS];
            return false;
        }

        return true;
    }

    /**
     * 账号数据库验证
     * @return bool
     */
    protected function _checkDbTable()
    {
        $this->_dbAuthAdapter = new Zend_Auth_Adapter_DbTable(
            Zend_Db_Table::getDefaultAdapter(),
            $this->_dbAuthAdapterConfig['table'],
            $this->_dbAuthAdapterConfig['identityColumn'],
            $this->_dbAuthAdapterConfig['credentialColumn']
        );

        $result = $this->_dbAuthAdapter->setIdentity($this->_authParams['identity'])
                                       ->setCredential(md5($this->_authParams['credential']))
                                       ->authenticate();

        if (!$result->isValid()) {
            $this->_authResultConfig['code']     = $result->getCode();
            $this->_authResultConfig['message']  = $this->_messages[$result->getCode()];
            $this->_getEmployee()->loginError($this->_authParams['identity']);
            return false;
        }

        //账号验证已通过,验证状态
        $row = $this->_dbAuthAdapter->getResultRowObject('status');

        //验证用户状态
        $valid = false;
        switch ($row->status) {
            case 0:
                $this->_authResultConfig['message'] = '账号未启用';
            break;

            case 2:
                $this->_authResultConfig['message'] = '此账号已被锁定';
            break;

            case 3:
                $this->_authResultConfig['message'] = '此账号已被禁用';
            break;

            default:
                $valid = true;
            break;
        }

        return $valid;
    }

    /**
     * 密保验证
     * @return bool
     */
    protected function _checkCryptoguard()
    {
        //如果绑定了密保的话，对密保就行验证
        if (!IG_Cryptoguard::isEnabled()) return true;

        $cryptoguard = IG_Cryptoguard::getInstance();
        if (!$cryptoguard->auth($this->_authParams['identity'], $this->_authParams['passpod'])) {
            $this->_authResultConfig['message'] = $cryptoguard->getMessage();
            return false;
        }

        return true;
    }


    /**
     * Zend_Auth_Result
     * @return Zend_Auth_Result
     */
    protected function _authResult()
    {
        return new Zend_Auth_Result($this->_authResultConfig['code'],
                                    $this->_authResultConfig['identity'],
                                    array($this->_authResultConfig['message']));
    }


    /**
     * @return Zend_Captcha_Image
     */
    public static function createVerifyCode() {
        $session = new Zend_Session_Namespace(self::$_verify['sessionname']);
        $setting = array(
            'font'      => APPLICATION_PATH . '/../data/ttf/VERDANA.TTF',
            //'fontsize'  => 12,
            'imgdir'    => APPLICATION_PATH . '/../public/cache/',
            'imgurl'    => '/cache/',
            'session'   => $session,
            'width'     => 100,
            //'height'    => 22,
            //'gcFreq'    => 0,
            'wordlen'   => 4
        );
        $captcha = new Zend_Captcha_Image($setting);
        $captcha->setDotNoiseLevel(0);    //设置点早点
        $captcha->setLineNoiseLevel(0);    //设置线噪点
        $captcha->setGcFreq(5);
        $captcha->setExpiration(5);        //设置保存时间
        $captcha->generate();
        return $captcha;
    }

    public static function isEnableVerify()
    {
        return self::$_verify['enable'];
    }

    public static function setEnableVerify($enable)
    {
        self::$_verify['enable'] = $enable;
    }

    /**
     * @return System_Model_Employee
     */
    protected function _getEmployee()
    {
        if (!isset($this->_employee)) {
            $this->_employee = new System_Model_Employee();
        }
        return $this->_employee;
    }
}